#include "mprocess.h"

mprocess::mprocess(QObject *parent) :
    QProcess(parent)
{
    clearArguments();
    setProcessChannelMode( QProcess::MergedChannels );

    connect(this, SIGNAL(readyRead()), this, SLOT(readFromClient()));
}

void mprocess::addArgument(const QString & a)
{
    if (program.isEmpty())  //第一个添加的为MPlayer.exe文件路径
    {
        program = a;
    }
    else                    //第二个添加的为参数
    {
        arg.append(a);
    }
}

void mprocess::clearArguments()
{
   // program = "";//ivan @2011.09.29 modify
    program.clear();
    arg.clear();
}

QStringList mprocess::arguments()
{
    QStringList l = arg;
    l.prepend(program);
    return l;
}

void mprocess::start()
{
//    if (this->isRunning())
//    {
//        this->writeToStdin("quit");
//    }
//    qDebug() << "progran------------------------->>" << program << arg;
    QProcess::start(program, arg);
}

bool mprocess::isRunning()
{
    //QProcess::ProcessState s = state();
    return (state() == QProcess::Running);
    //return (state() == QProcess::Starting);
}

void mprocess::writeToStdin(QString text)
{
    if (isRunning())
    {
        //qDebug("MplayerProcess::writeToStdin");
        write( text.toLocal8Bit() + "\n");
    } else
    {
//        qWarning("mprocess::writeToStdin: process not running");
    }

}

void mprocess::readFromClient()
{
//    QByteArray output = this->readAllStandardOutput();
//    QString data = output;

//    if (data.contains("Exiting... (End of file)"))
//    {
//        qDebug() << "data contans Exiting... (End of file)" << program << arg;
//        this->writeToStdin("play -loop 0 " + arg.at(arg.count() - 1));
//        qDebug() << "play end===================>";
//        emit mediaPlayEnd();
//    }

    //    if (data.contains("ANS_TIME_POSITION"))
    //    {
    //        int pos = data.indexOf("ANS_TIME_POSITION=");
    //        QString timePos = data.remove(0, pos+18);
    //        timePos.remove("\n");
    //        emit mplayerTimePos(timePos.toFloat());
    //        qDebug() << "current time pos==========>>>" << timePos;
    //    }

}
